#import "SMHomeListController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <MJRefresh/MJRefresh.h>
#import "../../Managers/Network/SMAPIClient.h"
#import "../../Managers/SMDataStore.h"
#import "../../Views/Components/SMBannerView.h"
#import "../../Models/SMBanner.h"
#import "../../Views/Cells/SMNewsCell.h"

static const NSInteger kPageSize = 10;

@interface SMHomeListController ()
@property(nonatomic, copy)   NSString *category;
@property(nonatomic, strong) NSMutableArray<NSDictionary *> *items; // {title,intro,time,image}
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, assign) BOOL hasMore;
@property(nonatomic, strong) SMBannerView *bannerView;
@end

@implementation SMHomeListController

- (instancetype)initWithCategory:(NSString *)category {
    if (self = [super initWithStyle:UITableViewStylePlain]) {
        _category = [category copy];
        _items = [NSMutableArray array];
        _page = 1; _hasMore = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = UIColor.systemBackgroundColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:SMNewsCell.class forCellReuseIdentifier:@"news"];

    // 分类独立 Banner
    self.bannerView = [[SMBannerView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
    self.bannerView.banners = [[SMDataStore shared] bannersForCategory:self.category];
    __weak typeof(self) weakSelf = self;
    self.bannerView.onTap = ^(SMBanner *b) {
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"[%@] Banner：%@", weakSelf.category, b.linkURL ?: @""]];
    };
    self.tableView.tableHeaderView = self.bannerView;

    // 刷新/加载更多
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - Refresh & Load
- (void)refresh { self.page = 1; self.hasMore = YES; [self requestPage:self.page isRefresh:YES]; }
- (void)loadMore {
    if (!self.hasMore) { [self.tableView.mj_footer endRefreshingWithNoMoreData]; return; }
    [self requestPage:self.page + 1 isRefresh:NO];
}

#pragma mark - Network with fallback
- (void)requestPage:(NSInteger)page isRefresh:(BOOL)isRefresh {
    NSDictionary *params = @{@"category": self.category ?: @"",
                             @"page": @(page),
                             @"pageSize": @(kPageSize)};
    __weak typeof(self) weakSelf = self;
    [[SMAPIClient shared] GET:@"market/list" parameters:params success:^(id json) {
        NSArray *data = [weakSelf parseArrayFromJSON:json];
        if (data.count == 0) {
            data = [[SMDataStore shared] homeNewsForCategory:weakSelf.category page:page pageSize:kPageSize];
        }
        [weakSelf applyData:data forPage:page isRefresh:isRefresh];
    } failure:^(NSError *error) {
        NSArray *data = [[SMDataStore shared] homeNewsForCategory:weakSelf.category page:page pageSize:kPageSize];
        [weakSelf applyData:data forPage:page isRefresh:isRefresh];
    }];
}

- (NSArray *)parseArrayFromJSON:(id)json {
    NSArray *arr = nil;
    if ([json isKindOfClass:NSDictionary.class] && [json[@"data"] isKindOfClass:NSArray.class]) {
        arr = json[@"data"];
    } else if ([json isKindOfClass:NSArray.class]) {
        arr = (NSArray *)json;
    }
    if (!arr) return @[];
    NSMutableArray *out = [NSMutableArray array];
    for (id obj in arr) {
        if (![obj isKindOfClass:NSDictionary.class]) continue;
        NSString *title = obj[@"title"] ?: obj[@"name"] ?: @"未知标题";
        NSString *intro = obj[@"intro"] ?: obj[@"summary"] ?: @"";
        NSString *time  = obj[@"time"]  ?: obj[@"updated_at"] ?: obj[@"date"] ?: @"刚刚";
        NSString *img   = obj[@"image"] ?: obj[@"cover"] ?: @"";
        [out addObject:@{@"title":title, @"intro":intro, @"time":time, @"image":img ?: @""}];
    }
    return out;
}

- (void)applyData:(NSArray *)data forPage:(NSInteger)page isRefresh:(BOOL)isRefresh {
    if (isRefresh) [self.items removeAllObjects];
    [self.items addObjectsFromArray:data];
    self.page = page;
    self.hasMore = (data.count >= kPageSize);
    [self.tableView reloadData];

    if (isRefresh) {
        [self.tableView.mj_header endRefreshing];
        if (self.hasMore) [self.tableView.mj_footer resetNoMoreData];
        else [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        if (self.hasMore) [self.tableView.mj_footer endRefreshing];
        else [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.items.count; }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 108; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SMNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"news" forIndexPath:indexPath];
    [cell configureWithDict:self.items[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // TODO: push 资讯详情页
}
@end
